//
//  AppDelegate.swift
//  Nairacup
//
//  Created by ec on 2024/9/9.
//

import UIKit
import AppsFlyerLib
import AppTrackingTransparency
import AdSupport

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = .white
        window?.makeKeyAndVisible()
        
        NotificationCenter.default.addObserver(self, selector: #selector(loginStatusChanged), name: NSNotification.Name(Adapt.loginStatusChanged), object: nil)

        loginStatusChanged()

        if #available(iOS 14, *) {
          ATTrackingManager.requestTrackingAuthorization { (status) in
            switch status {
            case .denied:
                print("AuthorizationSatus is denied")
            case .notDetermined:
                print("AuthorizationSatus is notDetermined")
            case .restricted:
                print("AuthorizationSatus is restricted")
            case .authorized:
                // 用户授权，获取 IDFA
                let idfa = ASIdentifierManager.shared().advertisingIdentifier
                print("IDFA: \(idfa)")
            @unknown default:
                fatalError("Invalid authorization status")
            }
          }
        }else {
            let idfa = ASIdentifierManager.shared().advertisingIdentifier
            print("IDFA: \(idfa)")
        }
        
        AppsFlyerLib.shared().appsFlyerDevKey = "<YOUR_DEV_KEY>"
        AppsFlyerLib.shared().appleAppID = "<APPLE_APP_ID>"
        let userId = UserDefaults.standard.string(forKey: Adapt.loginUserId) ?? Adapt.idfa
        AppsFlyerLib.shared().customerUserID = userId
        AppsFlyerLib.shared().start() { res, err in
            
        }

        requestStaticLogic()

        return true
    }
    
    @objc
    func loginStatusChanged() {
        let userId = UserDefaults.standard.string(forKey: Adapt.loginUserId) ?? Adapt.idfa
        window?.rootViewController = NavController(rootViewController: userId.isEmpty ? LoginViewController(nibName: "LoginViewController", bundle: nil) : HomeViewController())
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
//        let userId = UserDefaults.standard.string(forKey: Adapt.loginUserId) ?? ""
//        if !userId.isEmpty {
//            AppsFlyerLib.shared().customerUserID = userId
//            AppsFlyerLib.shared().start()
//        }
        requestVersion()
    }

    func requestVersion() {
        var version = "1"
        if let infoDictionary = Bundle.main.infoDictionary, let versionString = infoDictionary["CFBundleVersion"] as? String {
            version = versionString
        }
        Request.shared.requestApi(.getVersion) { [weak self] response in
            if (response["code"] as? Int) == 200, let data = response["data"] as? [String: Any], !data.keys.isEmpty, let code = data["code"] as? String, version != code {
                let must = data["must"] as? Int ?? 0
                let url = data["url"] as? String ?? ""
                let tips = data["tips"] as? String ?? ""
                let v = UpgradeView(frame: UIScreen.main.bounds)
                v.clickUpgrade = {
                    UIApplication.shared.open(URL(string: url)!)
                }
                if tips.isEmpty {
                    v.contentLabel.text = tips
                }
                v.cancelBtn.isHidden = must == 1
                v.closeBtn.isHidden = must == 1
                self?.window?.addSubview(v)
            }
        }
    }

    func requestStaticLogic() {
        let userId = UserDefaults.standard.string(forKey: Adapt.loginUserId) ?? Adapt.idfa
        if userId.isEmpty {
            return
        }
        var version = "1.0.0"
        if let infoDictionary = Bundle.main.infoDictionary {
            if let versionString = infoDictionary["CFBundleShortVersionString"] as? String {
                version = versionString
            }
        }
        Request.shared.requestApi(.staticLogin(version: version)) { response in
            if (response["code"] as? Int) == 200 {
                if let data = response["data"] as? [String: Any], let userId = data["userId"] as? String, let sessionId = data["sessionId"] as? String {
                    UserDefaults.standard.setValue(sessionId, forKey: Adapt.loginSessionId)
                    UserDefaults.standard.setValue(userId, forKey: Adapt.loginUserId)
                    if let jsonData = try? JSONSerialization.data(withJSONObject: data, options: .prettyPrinted), let jsonString = String(data: jsonData, encoding: .utf8) {
                        UserDefaults.standard.setValue(jsonString, forKey: Adapt.loginUserInfo)
                    }
                }
            }
        }
    }

}

